<template>
    <el-card>
        <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="120px">
            <el-form-item label="前端服务名：" prop="service">
                 <el-select v-model="queryParams.service" placeholder="请选择" size="small">
                    <el-option v-for="item in FrontendList" :label="item" :key="item" :value="item"></el-option>
                  </el-select>
            </el-form-item>
            <el-form-item label="前端API路径：" prop="path">
                <el-input v-model="queryParams.path" placeholder="接口名" size="small"></el-input>
            </el-form-item>
             <el-form-item label="熔断策略：" prop="strategy">
                 <el-select v-model="queryParams.strategy" placeholder="请选择" size="small">
                    <el-option v-for="item in strategyArr" :label="item.label" :key="item.value" :value="item.value"></el-option>
                  </el-select>
            </el-form-item>
            <el-form-item >
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
            </el-form-item>
        </el-form>
         <el-row :gutter="10">
            <el-col :span="24">
                <div style="margin-bottom: 10px">
                    <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                </div>
            </el-col>
        </el-row>
        <el-table :data="tableData" border style="width: 100%" size="small">
            <el-table-column type="index" label="#" width="50"></el-table-column>
            <el-table-column label="前端服务名" prop="service"></el-table-column>
            <el-table-column label="前端API路径" prop="path"></el-table-column>
            <el-table-column label="熔断策略" prop="strategy">
                <template slot-scope="{row}">
                    <span v-if="row.strategy===1">异常比例</span>
                    <span v-if="row.strategy===2">异常数</span>
                </template>
            </el-table-column>
            <el-table-column label="比例阀值" prop="ratioThreshold"></el-table-column>
            <el-table-column label="异常数" prop="exceptionCount"></el-table-column>
            <el-table-column label="最小请求数" prop="minRequestCount"></el-table-column>
            <el-table-column label="熔断时长（秒）" prop="timeWindow" width="200"></el-table-column>
            <el-table-column label="统计时长（秒）" prop="statInterval"></el-table-column>
            <el-table-column label="操作" width="200" align="center">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
         <el-pagination
                v-show="total>0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
                :current-page="1"
                :page-sizes="[10, 20, 30, 40,50,100]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                class="pagination-container"
                :total="total">
        </el-pagination>
        <el-dialog :title="`${formTitle} 熔断规则`" :visible.sync="dialogVisible" width="50%">
            <el-form :model="form" ref="form" label-width="170px" :rules="rules" :disabled="mode==='view'">
              <el-form-item label="前端服务名" required prop="service">
                  <el-select v-model="form.service" placeholder="请选择" size="small">
                    <el-option v-for="item in FrontendList" :label="item" :key="item" :value="item"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="前端API路径" prop="path">
                  <el-input v-model="form.path" placeholder="请输入前端API路径" size="small"></el-input>
                  <div class="tips">如果接口URL为http://网关IP:port/proxy/user-service/user/list, 则输入/user/list，如果不配置路径则按服务熔断</div>
              </el-form-item>
              <el-form-item label="熔断策略：" required prop="strategy">
                 <el-radio-group v-model="form.strategy">
                    <el-radio :label="1">异常比例</el-radio>
                    <el-radio :label="2">异常数</el-radio>
                 </el-radio-group>
              </el-form-item>
              <el-form-item label="比例阀值：" required prop="ratioThreshold" v-if="form.strategy===1">
                <el-input-number v-model="form.ratioThreshold" size="small" :min="0" :max="1" :step="0.1"></el-input-number>
                <div class="tips">异常的请求比例阈值，超过该值触发熔断，默认值为0.5</div>
              </el-form-item>
               <el-form-item label="异常数：" required prop="exceptionCount" v-if="form.strategy===2">
                <el-input-number v-model="form.exceptionCount" size="small" :min="1" :step="1"></el-input-number>
                <div class="tips">异常的请求数，超过该值触发熔断，默认值为50</div>
              </el-form-item>
              <el-form-item label="最小请求数：" required prop="minRequestCount">
                <el-input-number v-model="form.minRequestCount" size="small" :min="1" :max="100000000000000000" :step="1"></el-input-number>
                <div class="tips">请求数小于该值时即使异常请求超出阈值也不会熔断，默认值为100</div>
              </el-form-item>
               <el-form-item label="熔断时长：" required prop="timeWindow">
                <el-input-number v-model="form.timeWindow" size="small" :min="1" :max="100000000000000000" :step="1"></el-input-number>
                <div class="tips">触发熔断后请求被熔断的时长，默认值为10</div>
              </el-form-item>
              <el-form-item label="统计时长：" required prop="statInterval">
                <el-input-number v-model="form.statInterval" size="small" :min="1" :max="100000000000000000" :step="1"></el-input-number>
                <div class="tips">熔断的统计时长，默认值为10</div>
              </el-form-item>
              <el-form-item label="恢复策略：" required prop="recoveryStrategy">
                 <el-radio-group v-model="form.recoveryStrategy">
                    <el-radio :label="1">尝试恢复
                        <el-tooltip class="item" effect="dark" content="熔断结束后放通一个请求进入，请求成功时恢复服务，请求失败则立即进入下一个熔断时长。" placement="bottom">
                           <i class="el-icon-question"></i>
                        </el-tooltip>
                    </el-radio>
                    <el-radio :label="2">逐步恢复
                        <el-tooltip placement="top">
                            <div slot="content">熔断结束后根据恢复时长按比例逐步放通请求，<br/>例如配置恢复时长5秒，则第1秒放通20%的请求，第2秒放通40%的请求,...，第5秒放通100%的请求。</div>
                             <i class="el-icon-question"></i>
                        </el-tooltip>
                    </el-radio>
                     <el-radio :label="3">立即恢复
                        <el-tooltip class="item" effect="dark" content="熔断结束后立即恢复服务，放通所有请求。" placement="bottom">
                           <i class="el-icon-question"></i>
                        </el-tooltip>
                     </el-radio>
                 </el-radio-group>
              </el-form-item> 
               <el-form-item label="恢复时长：" required prop="recoveryTimeWindow" v-if="form.recoveryStrategy===2">
                <el-input-number v-model="form.recoveryTimeWindow" size="small" :min="5" :step="1"></el-input-number>秒
                <div class="tips">熔断结束后的恢复时长，默认值为5</div>
              </el-form-item> 
               <el-form-item label="熔断响应ContentType：" prop="responseContentType">
                <el-input v-model="form.responseContentType" placeholder="请输入ContentType" size="small"></el-input>
                <div class="tips">如果不配置则使用默认规则里的熔断响应ContentType</div>
              </el-form-item>  
              <el-form-item label="熔断响应报文：" prop="responseContent">
                <el-input v-model="form.responseContent" placeholder="请输入ContentType" size="small"></el-input>
                <div class="tips">如果不配置则使用默认规则里的熔断响应报文</div>
              </el-form-item>          
            </el-form>
            <span slot="footer" class="dialog-footer" v-if="mode!=='view'">
                <el-button @click="dialogVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="submitForm('form')" size="small">确 定</el-button>
            </span>
        </el-dialog>
   </el-card>
</template>

<script>
import { getFrontendList,getInterfaceList,save,remove,update } from '@/api/fuse/interface.api'
    export default {
        data() {
          return {
            queryParams: {
                current: 1,
                size: 10,
                serviceName: undefined,
                name: undefined,
                path: undefined,
                opType: undefined,
                opTimeStart: '',
                opTimeEnd: ''
            },
            tableData: [],
            strategyArr: [
                {label: '异常比例',value: 1},
                {label: '异常数',value: 2},
            ],
            total: 0,
            FrontendList: [],
            formTitle: '新增',
            dialogVisible: false,
            form: {
                strategy: 1,
                ratioThreshold: 0.5,
                minRequestCount: 100,
                timeWindow: 10,
                statInterval: 10,
                exceptionCount: 50,
                recoveryTimeWindow: 5
            },
            rules: {
                service: [{ required: true, message: '必填', trigger: 'blur' }],
                recoveryStrategy: [{ required: true, message: '必填', trigger: 'blur' }],
            },
            mode: 'add'
          }
        },
        mounted() {
            this.getList();
            this.getFrontendDict();
        },
        filters: {
            statusFilter(value) {
                if(value===1) {
                    return '未发布';
                }
            }
        },
        methods: {
            handleAdd() {
                this.dialogVisible = true;
                this.mode = 'add';
            },
            submitForm(formName) {
                this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    if(this.form.id) {
                         const result = await update(this.form);
                        if(result.code === 200) {
                            this.$message.success('修改成功');
                            this.dialogVisible = false;
                            this.getList();
                        } 
                    }else {
                        const result = await save(this.form);
                        if(result.code === 200) {
                            this.$message.success('保存成功');
                            this.dialogVisible = false;
                            this.getList();
                        } 
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
                });
            },
            handleView(row) {
                this.form = JSON.parse(JSON.stringify(row));
                this.dialogVisible = true;
                this.mode = 'view';
                this.formTitle = '查看';
            },
            handleEdit(row) {
                this.form = JSON.parse(JSON.stringify(row));
                this.dialogVisible = true;
                this.mode = 'edit';
                this.formTitle = '编辑';
            },
            handleDelete(id) {
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const result = await remove(id);
                    if(result.code === 200) {
                            this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList();
                    }else {
                        this.$message.error(result.data.msg);
                    }
                }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
            },
            async getFrontendDict() {
                const result = await getFrontendList();
                 if(result.code === 200) {
                    this.FrontendList = result.data;
                }
            },
            async getList() {
                const result = await getInterfaceList(this.queryParams);
                if(result.code === 200) {
                    this.tableData = result.data.records;
                    this.total = result.data.total
                }
            },
              // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
        }
    }
</script>
<style lang="scss" scoped>
.pagination-container {
    padding: 10px;
    text-align: right;
}
.tips {
    color: #999;
    font-size: 12px;
    line-height: normal;
    margin-top: 8px;
    display: block; 
}
</style>